package xyz.itpath.tools;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @author zhaom
 * @date 2021/11/10 - 9:38
 * <p>
 * 队列缓存,缓存指定数量的数据
 */
public class QueueCacheUtil<T,O> {

    private final LinkedList<T> CACHE_KEYS = new LinkedList<>();
    private static final int CACHE_SIZE = 1000;
    private final Map<T, O> CACHE = new HashMap<>();

    public void putCache(T key, O o) {
        if (CACHE_KEYS.size() > CACHE_SIZE - 1) {
            T s = CACHE_KEYS.removeLast();
            removeCache(s);
        }
        CACHE_KEYS.addFirst(key);
        CACHE.put(key, o);
    }

    private void removeCache(T key) {
        CACHE.remove(key);
    }

    public boolean hasCache(T key) {
        return CACHE.containsKey(key);
    }

    public O getCache(T key) {
        return CACHE.get(key);
    }

}
